<?php

namespace app\admin\controller\coll;

use app\common\controller\Backend;
use app\common\model\data\Voucher;
use app\common\model\Storehouse;
use app\common\model\supplier\Supplier;
use think\Db;
use app\common\model\coll\Log;
use app\common\model\customer\Customer;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Analysis extends Backend
{
    
    /**
     * Analysis模型对象
     * @var \app\common\model\coll\Analysis
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\coll\Analysis;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $this->handlefilter();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                    ->with(['storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','source','cost','operator','company','status','is_income','controller','settle_name','number','createtime','source_id','explain']);
                $row->visible(['storehouse']);
                $row->getRelation('storehouse')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $source = $this->model->an_source();
            $statuss = $this->model->an_status();
            foreach ($list as $k=>$v){
                $mm = $this->getmaoli($v['source'],$v['source_id']);
                foreach ($mm as $key =>$val){
                    $list[$k][$key]=$val;
                }
                $list[$k]['source'] = $source[$v['source']];
                $Log = new Log;
                $paymoney = $Log->where(array('analysis_id'=>$v['id'],'status'=>1))->sum('price');
                $list[$k]['paymoney'] = $paymoney;
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $statuss[$v['status']];
                $list[$k]['analysis.createtime'] = $v['createtime'];
            }
            $filter = json_decode(input('filter'));
            if(!empty($filter)){
                $arr = $this->getcount($filter);
                $result = array("total" => $total, "rows" => $list,'allcost'=>$arr['allcost'],
                    'yescost'=>$arr['yescost'],
                    'notcost'=>$arr['notcost'],);
            }else{
                $result = array("total" => $total, "rows" => $list,'allcost'=>0,
                    'yescost'=>0,
                    'notcost'=>0,);
            }
            return json($result);
        }
        return $this->view->fetch();
    }
    public function getmaoli($source,$source_id){
        $cost = 0;
        $sale = 0;
        switch ($source){
//            case 2://采购入库单
//                 $list = Db::name('purchase_goods')
//                    ->where(array('purchase_enter_id'=>$source_id))
//                    ->select();
//
//                break;
//            case 3://采购退货单
//                break;
//            case 4://非经营性调整
//                break;
//            case 5://同价调拨单
//                break;
            case 7://销售出库单
                $list = Db::name('sales_checkout_goods')
                    ->where(array('sales_checkout_id'=>$source_id))
                    ->field('goods_num,costPrice,sale_price')
                    ->select();
                foreach ($list as $v){
                    $cost += $v['costPrice']*$v['goods_num'];
                    $sale += $v['sale_price']*$v['goods_num'];
                }
                return  array(
                    'profit'=> number_format($sale-$cost,2),
                    'costprice'=>number_format($cost,2),
                    'maoli'=>number_format(empty($sale)?0:($sale-$cost)/$sale,2)*100 .'%',
                );
                break;
            case 8://销售换货单
                $list = Db::name('sales_change_goods')
                    ->where(array('sales_change_id'=>$source_id))
                    ->field('goods_num,costPrice,goods_type,sale_price')
                    ->select();
                $rucost = 0;
                $jincost = 0;
                foreach ($list as $v){
                    if($v['goods_type'] ==1){
                        $rucost +=$v['costPrice']*$v['goods_num'];//退货的成本
                        $cost +=($v['sale_price']-$v['costPrice'])*$v['goods_num'];//退货的毛利
                    }else{
                        $jincost +=$v['costPrice']*$v['goods_num'];//换货的成本
                        $sale +=($v['sale_price']-$v['costPrice'])*$v['goods_num'];//换货的毛利
                    }
                }
                $cost1 = $sale-$cost;
                $cost = $jincost-$rucost;
//                dump($sale);
//                dump($cost1);
//                exit;

                return  array(
                    'costprice'=>number_format($cost,2),
                    'profit'=> number_format($cost1,2),
                    'maoli'=>number_format(empty($cost)?0:$cost1/$cost,3)*100 .'%',
                );
                break;
            case 9://销售退货单
                $list = Db::name('sales_retreat_goods')
                    ->where(array('sales_retreat_id'=>$source_id))
                    ->field('goods_num,costPrice,sale_price')
                    ->select();
                foreach ($list as $v){
                    $cost += $v['costPrice']*$v['goods_num'];
                    $sale += $v['sale_price']*$v['goods_num'];
                }
                return  array(
                    'profit'=> number_format($sale-$cost,2),
                    'costprice'=>number_format($cost,2),
                    'maoli'=>number_format(empty($sale)?0:($sale-$cost)/$sale,2)*100 .'%',
                );
                break;
//            case 10://报损单
//                break;
//            case 11://报溢单
//                break;
            case 12://厂家直发
                $list = Db::name('factory_sales_goods')
                    ->where(array('factory_sales_id'=>$source_id))
                    ->field('goods_num,unit_price,sale_price')
                    ->select();
                foreach ($list as $v){
                    $cost += $v['unit_price']*$v['goods_num'];
                    $sale += $v['sale_price']*$v['goods_num'];
                }
                return  array(
                    'profit'=> number_format($sale-$cost,2),
                    'costprice'=>number_format($cost,2),
                    'maoli'=>number_format(empty($sale)?0:($sale-$cost)/$sale,2)*100 .'%',
                );
                break;
//            case 13://采购入库分摊单
//                break;
//            case 15://差价单据
//                break;
            default:
                return [];
        }
    }
    public function jump($ids){
        $row = $this->model->find($ids);
        if($row['source'] == 16){

            $url = $row['controller'].'/detail?ids='.$row['source_id'].'&is_finance=1';
        }else{
            $url = $row['controller'].'/detail?ids='.$row['source_id'].'&is_finance=1';
        }
        $this->success('','',$url);
    }
    public function pay($ids = null){
        $row = $this->model->find($ids);

        if ($this->request->isAjax())
        {
            $params = input('row/a');
            if(empty($params['price'])){
                $this->error('金额不能为空');
            }

            if(empty($params['thumb']) && empty($params['remark'])){
                $this->error('凭证或备注至少选一项');
            }
            $discount = $params['discount'];
//            if($discount >10){
//                $this->error('优惠金额受限');
//            }
            //判断已收等
            if($params['price']+$discount>$row['cost']){
                $this->error('金额超过上线');
            }

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            $data = array(
                    'analysis_id'=>$row['id'],
                    'price'=>$params['price'],
                    'image'=>$params['thumb'],
                    'pay_id'=>$params['pay_id'],
                    'pay_time'=>strtotime($params['pay_time']),
                    'make_time'=>strtotime($params['make_time']),
//                    'discount'=>$params['discount'],
                    'remark'=>$params['remark'],
                    'is_income'=>$row['is_income'],
                     'admin_id' => session('admin')['id'],
                     'group_id' => $group['group_id'],
                     'company' => $group['name'],
                     'settle_name' => $row['settle_name'],
                     'handler' => $row['operator'],
                     'handler_id' => $row['admin_id'],
                     'operator' => session('admin')['nickname'],
                );
            $Log = new Log;
            $history = $Log->where(array('analysis_id'=>$ids,'status'=>1))->sum('price');

            $status = 2;
            if(!empty($discount)){
                if(($discount+$data['price']+$history)>$row['cost']){
                    $this->error('金额不一致1');
                }
                if(($discount+$data['price']+$history) == $row['cost']){
                    $status = 3;
                }
            }else{
                if(($data['price']+$history)>$row['cost']){
                    $this->error('金额不一致2');
                }
                if(($data['price']+$history) == $row['cost']){
                    $status = 3;
                }
            }
            $data['storehouse_id'] = $row['storehouse_id'];


            $num = Db::name('analysis_collection')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();

//            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

//            $cdata = array(
//                'number'=>'XS-T-'.date('Y-m-d').'-'.getnumber($num),
//                'paymoney'=>$collect_money,
//                'image'=>$thumb,
//                'remark'=>$remark,
//                'is_income'=>$pay_type,
//                'admin_id' => session('admin')['id'],
//                'group_id' => $group['group_id'],
//                'pay_time'=>strtotime(input('pay_time')),
//                'make_time'=>strtotime(input('make_time')),
//                'company' => $group['name'],
//                'settle_name' => $settle_name,
//                'operator' => session('admin')['nickname'],
//                'storehouse_id' => $storehouse_id,
//                'pay_id'=>$pay_id,
//                'discount'=>$discount,
//                'createtime'=>time(),
//            );



            Db::startTrans();
            try {




                $Log = new Log;
                $res = $Log->save($data);
                if (!$res) {
                    throw new Exception('数据异常');
                }
                if ($discount && $res) {
                    $newdata = $data;
                    $newdata['price'] = $discount;
                    $newdata['is_income'] = 3;
                    $newdata['storehouse_id'] = $row['storehouse_id'];
                    $Log = new Log;
                    $res = $Log->save($newdata);
                    if (!$res) {
                        throw new Exception('数据异常');
                    }
                }
                $res = $this->model->save(array('status'=>$status),array('id'=>$ids));
                if (!$res) {
                    throw new Exception('数据异常');
                }
                Db::commit();;
                return  array(
                  'code'=>1,
                  'msg'=>'添加成功',
                );
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $Log = new Log;
        $paymoney = $Log->where(array('analysis_id'=>$ids,'status'=>1))->sum('price');

        $paymodel = new \app\common\model\coll\Pay();
        $plist = $paymodel->where(array('status'=>'normal'))->select();

        $statuss = $this->model->getStatusList();
        $types = $this->model->an_source();
        $row['source'] = $types[$row['source']];

//        $row['is_income'] = $statuss[$row['is_income']];
        $this->assign('plist',$plist);
        $this->assign('row',$row);
        $this->assign('paymoney',$paymoney);
        return $this->view->fetch();
    }
    public function check(){
        $ids = json_decode(input('ids'),true);
        if(empty($ids)){
            $this->error('选择内容为空');
        }
        $list = $this->model->where(array('id'=>array('in',$ids)))->select();
        $source = 0;
        $obj_id = 0;
        $is_income = 0;
        foreach ($list as $v){
            if($source == 0){
                $source = $v['source'];
            }
            if($is_income == 0){
                $is_income = $v['is_income'];
            }
//            if($source >0 && $source != $v['source']){
//                $this->error('单据不统一');
//            }
            if($obj_id == 0){
                $obj_id = $v['obj_id'];
            }
            if($obj_id >0 && $obj_id != $v['obj_id']){
                $this->error('结算单位不统一');
            }
        }
        if($is_income == 1){
            $this->success('效验成功','/coll/analysis/batch');
        }else{
            $this->success('效验成功','/coll/analysis/batchs');
        }

    }
    //批量收
    public function batch(){

        $ids = explode(',',input('ids'));
        $list = $this->model->where(array('id'=>array('in',$ids)))->select();

        $Log = new Log;
        $paymoney = $Log->where(array('analysis_id'=>array('in',$ids),'status'=>1))->sum('price');

        $allmoney  =0;
        foreach ($list as $v){
            if($v['status'] >2){
                $this->error('状态异常');
            }
            $allmoney+=$v['cost'];
        }
        $row = $list[0];
        if(empty($row)){
            $this->error('暂无数据');
        }
        if ($this->request->isAjax())
        {
            $pay_id = input('pay_id/d',0);

            $discount = input('discount/d',0);
//            if(input('discount') >10){
//                $this->error('优惠金额受限');
//            }
            if(empty(input('thumb')) && empty(input('remark'))){
                $this->error('凭证或备注至少选一项');
            }
            $pay = floatval(input('pay',0));

            if(empty($pay) || $pay+$paymoney+$discount>$allmoney){
                $this->error('收入金额不能为0或者超出上限');
            }

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            Db::startTrans();
            try {
                $bids = [];
                $balance = $pay+$discount;
                $paypay = 0;
                $alist = $this->model->where(array('id'=>array('in',$ids)))->order('id','ASC')->select();
                $analysis_id = 0;
                foreach ($alist as $v){
                    if($v['status'] ==2){
                        $analysis_id = $v['id'];

                        $costcost = Db::name('analysis_log')->where(array('status'=>1,'analysis_id'=>$v['id']))->sum('price');
                        if($balance>$v['cost']-$costcost){
                            Db::name('analysis')->where(array('id'=>$v['id']))->update(array('status'=>3));
                        }
                        if($balance >$v['cost']-$costcost){
                            $price = $v['cost']-$costcost-$discount;
                        }else{
                            $price = $balance-$discount;
                        }
                        $balance -=$v['cost']-$costcost;
                        $data = array(
                            'analysis_id'=>$v['id'],
                            'pay_id'=>$pay_id,
                            'price'=>$price,
                            'image'=>input('thumb'),
                            'remark'=>input('remark'),
                            'pay_time'=>strtotime(input('pay_time')),
                            'make_time'=>strtotime(input('make_time')),
                            'is_income'=>$row['is_income'],
                            'admin_id' => session('admin')['id'],
                            'group_id' => $group['group_id'],
                            'company' => $group['name'],
                            'settle_name' => $row['settle_name'],
                            'operator' => session('admin')['nickname'],
                            'storehouse_id' => $row['storehouse_id'],
                            'handler' => $row['operator'],
                            'handler_id' => $row['admin_id'],
                        );
                        $Log = new Log;
                        $Log->save($data);

                    }else{
                        if($balance >$v['cost']){
                            $analysis_id = $v['id'];
                            $bids[] = $v['id'];
                            Db::name('analysis')->where(array('id'=>$v['id']))->update(array('status'=>3));
                            $balance -=$v['cost'];
                            $paypay+=$v['cost'];
                        }elseif ($balance ==$v['cost']){
                            $analysis_id = $v['id'];
                            $bids[] = $v['id'];
                            Db::name('analysis')->where(array('id'=>$v['id']))->update(array('status'=>3));
                            $balance -=$v['cost'];
                            $paypay+=$v['cost']-$discount;
                        }else{
                            if($balance <=0){
                                break;
                            }else{
                                $analysis_id = $v['id'];
                                //不够的单独处理
                                Db::name('analysis')->where(array('id'=>$v['id']))->update(array('status'=>2));
                                $data = array(
                                    'analysis_id'=>$v['id'],
                                    'price'=>$balance-$discount,
                                    'image'=>input('thumb'),
                                    'remark'=>input('remark'),
                                    'is_income'=>$row['is_income'],
                                    'admin_id' => session('admin')['id'],
                                    'group_id' => $group['group_id'],
                                    'pay_time'=>strtotime(input('pay_time')),
                                    'make_time'=>strtotime(input('make_time')),
                                    'company' => $group['name'],
                                    'settle_name' => $row['settle_name'],
                                    'operator' => session('admin')['nickname'],
                                    'storehouse_id' => $row['storehouse_id'],
                                    'handler' => $row['operator'],
                                    'handler_id' => $row['admin_id'],
                                    'pay_id'=>$pay_id,
                                );
                                $Log = new Log;
                                $Log->save($data);
                                break;
                            }

                        }
                    }

                }

                if(!empty($bids)){
                    //                $this->model->save(array('status'=>3),array('id'=>array('in',$ids)));
                    //够的直接处理
                    $data = array(
                        'analysis_id'=>implode(',',$bids),
                        'price'=>$paypay,
                        'image'=>input('thumb'),
//                    'discount'=>$params['discount'],
                        'remark'=>input('remark'),
                        'is_income'=>$row['is_income'],
                        'admin_id' => session('admin')['id'],
                        'group_id' => $group['group_id'],
                        'pay_time'=>strtotime(input('pay_time')),
                        'make_time'=>strtotime(input('make_time')),
                        'company' => $group['name'],
                        'settle_name' => $row['settle_name'],
                        'operator' => session('admin')['nickname'],
                        'storehouse_id' => $row['storehouse_id'],
                        'handler' => $row['operator'],
                        'handler_id' => $row['admin_id'],
                        'pay_id'=>$pay_id,
                    );
                    $Log = new Log;
                    $Log->save($data);
                }
                //优惠不为空
                if(!empty($discount)){
                    if(empty($analysis_id)){
                        throw new Exception('联系管理员');
                    }
                    $rerre = Db::name('analysis_log')->insert(array(
                        'price'=>$discount,
                        'analysis_id'=>$analysis_id,
                        'image'=>input('thumb'),
                        'remark'=>input('remark'),
                        'is_income'=>3,
                        'admin_id' => session('admin')['id'],
                        'group_id' => $group['group_id'],
                        'pay_time'=>strtotime(input('pay_time')),
                        'make_time'=>strtotime(input('make_time')),
                        'company' => $group['name'],
                        'settle_name' => $row['settle_name'],
                        'operator' => session('admin')['nickname'],
                        'storehouse_id' => $row['storehouse_id'],
                        'handler' => $row['operator'],
                        'handler_id' => $row['admin_id'],
                        'pay_id'=>$pay_id,
                        'createtime'=>time()
                    ));
                    if(!$rerre){
                        throw new Exception('联系管理员');
                    }
                }
                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'处理成功',
                );
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

            dump(input());
            exit;
        }



        $statuss = $this->model->getStatusList();
        $types = $this->model->an_source();
        $row['source'] = $types[$row['source']];

//        $row['is_income'] = $statuss[$row['is_income']];



        $paymodel = new \app\common\model\coll\Pay();
        $plist = $paymodel->where(array('status'=>'normal'))->select();


        $this->assign('plist',$plist);
        $this->assign('row',$row);
        $this->assign('paymoney',$paymoney);

        $this->assign('list',$list);
        $this->assign('allmoney',$allmoney);
        return $this->view->fetch();
    }
    //批量付钱
    public function batchs(){

        $ids = explode(',',input('ids'));
        $list = $this->model->where(array('id'=>array('in',$ids)))->select();
        $allmoney  =0;
        foreach ($list as $v){
            if($v['status'] >2){
                $this->error('状态异常');
            }
            $allmoney+=$v['cost'];
        }
        $row = $list[0];
        if(empty($row)){
            $this->error('暂无数据');
        }
        $Log = new Log;
        $paymoney = $Log->where(array('analysis_id'=>array('in',$ids),'status'=>1))->sum('price');

        if ($this->request->isAjax())
        {
            $discount = input('discount/d',0);
            $pay = floatval(input('pay',0));
            if(empty($pay) || $pay+$paymoney+$discount>$allmoney){
                $this->error('支出金额不能为0或者超出上限');
            }

            if(empty(input('thumb')) && empty(input('remark'))){
                $this->error('凭证或备注至少选一项');
            }
            $pay_id = input('pay_id/d',0);


            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            Db::startTrans();
            try {

                $bids = [];
                $analysis_id = 0;
                $balance = $pay+$discount;
                $paypay = 0;
                $alist = $this->model->where(array('id'=>array('in',$ids)))->order('id','ASC')->select();
                foreach ($alist as $v){
                    if($v['status'] ==2){
                        $analysis_id = $v['id'];
                        $costcost = Db::name('analysis_log')->where(array('status'=>1,'analysis_id'=>$v['id']))->sum('price');
                        if($balance>$v['cost']-$costcost){
                            Db::name('analysis')->where(array('id'=>$v['id']))->update(array('status'=>3));
                        }

                        if($balance >$v['cost']-$costcost){
                            $price = $v['cost']-$costcost-$discount;
                        }else{
                            $price = $balance-$discount;
                        }

                        $balance -=$v['cost']-$costcost;
                        $data = array(
                            'analysis_id'=>$v['id'],
                            'pay_id'=>$pay_id,
                            'price'=>$price,
                            'image'=>input('thumb'),
                            'remark'=>input('remark'),
                            'pay_time'=>strtotime(input('pay_time')),
                            'make_time'=>strtotime(input('make_time')),
                            'is_income'=>$row['is_income'],
                            'admin_id' => session('admin')['id'],
                            'group_id' => $group['group_id'],
                            'company' => $group['name'],
                            'settle_name' => $row['settle_name'],
                            'operator' => session('admin')['nickname'],
                            'storehouse_id' => $row['storehouse_id'],
                            'handler' => $row['operator'],
                            'handler_id' => $row['admin_id'],
                        );
                        $Log = new Log;
                        $Log->save($data);
                    }else{
                        if($balance >$v['cost']){
                            $analysis_id = $v['id'];
                            $bids[] = $v['id'];
                            Db::name('analysis')->where(array('id'=>$v['id']))->update(array('status'=>3));
                            $balance -=$v['cost'];
                            $paypay+=$v['cost'];

                        }elseif ($balance ==$v['cost']){
                            $analysis_id = $v['id'];
                            $bids[] = $v['id'];
                            Db::name('analysis')->where(array('id'=>$v['id']))->update(array('status'=>3));
                            $balance -=$v['cost'];
//                            $paypay+=$v['cost'];
                            $paypay+=$v['cost']-$discount;
                        }else{
                            if($balance<=0){
                                break;
                            }else{
                                $analysis_id = $v['id'];
                                //不够的单独处理
                                Db::name('analysis')->where(array('id'=>$v['id']))->update(array('status'=>2));
                                $data = array(
                                    'analysis_id'=>$v['id'],
                                    'price'=>$balance-$discount,
                                    'image'=>input('thumb'),
                                    'remark'=>input('remark'),
                                    'is_income'=>$row['is_income'],
                                    'admin_id' => session('admin')['id'],
                                    'group_id' => $group['group_id'],
                                    'pay_time'=>strtotime(input('pay_time')),
                                    'make_time'=>strtotime(input('make_time')),
                                    'company' => $group['name'],
                                    'settle_name' => $row['settle_name'],
                                    'operator' => session('admin')['nickname'],
                                    'storehouse_id' => $row['storehouse_id'],
                                    'handler' => $row['operator'],
                                    'handler_id' => $row['admin_id'],
                                    'pay_id'=>$pay_id,
                                );
                                $Log = new Log;
                                $Log->save($data);
                                break;
                            }

                        }
                    }

                }
//                $this->model->save(array('status'=>3),array('id'=>array('in',$ids)));
                //够的直接处理
             if(!empty($bids)){
                 $data = array(
                     'analysis_id'=>implode(',',$bids),
                     'price'=>$paypay,
                     'image'=>input('thumb'),
//                    'discount'=>$params['discount'],
                     'remark'=>input('remark'),
                     'is_income'=>$row['is_income'],
                     'admin_id' => session('admin')['id'],
                     'group_id' => $group['group_id'],
                     'pay_time'=>strtotime(input('pay_time')),
                     'make_time'=>strtotime(input('make_time')),
                     'company' => $group['name'],
                     'settle_name' => $row['settle_name'],
                     'operator' => session('admin')['nickname'],
                     'storehouse_id' => $row['storehouse_id'],
                     'handler' => $row['operator'],
                     'handler_id' => $row['admin_id'],
                     'pay_id'=>$pay_id,
                 );
                 $Log = new Log;
                 $Log->save($data);
             }
                //优惠不为空
                if(!empty($discount)){
                    if(empty($analysis_id)){
                        throw new Exception('联系管理员');
                    }
                    $rerre = Db::name('analysis_log')->insert(array(
                        'price'=>$discount,
                        'analysis_id'=>$analysis_id,
                        'image'=>input('thumb'),
                        'remark'=>input('remark'),
                        'is_income'=>3,
                        'admin_id' => session('admin')['id'],
                        'group_id' => $group['group_id'],
                        'pay_time'=>strtotime(input('pay_time')),
                        'make_time'=>strtotime(input('make_time')),
                        'company' => $group['name'],
                        'settle_name' => $row['settle_name'],
                        'operator' => session('admin')['nickname'],
                        'storehouse_id' => $row['storehouse_id'],
                        'handler' => $row['operator'],
                        'handler_id' => $row['admin_id'],
                        'pay_id'=>$pay_id,
                        'createtime'=>time()
                    ));
                    if(!$rerre){
                        throw new Exception('联系管理员');
                    }
                }

                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'处理成功',
                );
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

            dump(input());
            exit;
        }



        $statuss = $this->model->getStatusList();
        $types = $this->model->an_source();
        $row['source'] = $types[$row['source']];

//        $row['is_income'] = $statuss[$row['is_income']];

        $paymodel = new \app\common\model\coll\Pay();
        $plist = $paymodel->where(array('status'=>'normal'))->select();


        $this->assign('plist',$plist);
        $this->assign('row',$row);
        $this->assign('paymoney',$paymoney);

        $this->assign('list',$list);
        $this->assign('allmoney',$allmoney);
        return $this->view->fetch();
    }
    public function export(){
        if($this->request->isPost()){
            $this->exportExcel();
            exit;
        }
        $this->assign('statuslist',$this->model->an_status());
        return $this->view->fetch();
    }
    public function exportExcel(){
        $start_time = input('start_time');
        $end_time = input('end_time');
        $status = input('status/a','');
        $type_id = input('type_id/d',2);
        $customer_id = input('customer_id/d',0);
        $supplier_id = input('supplier_id/d',0);
        $admin_id = input('admin_id/d',0);
        $storehouse_id = input('storehouse_id/d',0);

        $where['status'] = array('<',4);
        if(!empty($status) && trim($status[0]) != 'null'){
            $status = explode(',',$status[0]);
            $where['status'] = array('in',$status);
        }


        if($admin_id>0){
            $where['admin_id'] = $admin_id;
        }
//        if($customer_id>0){
//            $where['obj_id'] = $customer_id;
//        }
//        $where = array('customer_id'=>$customer_id);
        if(empty($start_time)){
            $start_time = 0;
        }
        if($type_id == 2){//付款类型  面向对象 供应商
//            $where['source'] = array('in',[1,2,3,7,8,11]);
            $where['is_income'] = 2;
            if($supplier_id>0){
                $ccrow = Supplier::get($supplier_id);
                $where['obj_id'] = $supplier_id;
                $company = $ccrow['nickname'];
                $nickname = $ccrow['contacts'];
                $mobile = $ccrow['mobile'];
                $zip_code = '';
                $address = '';
                $tax_number = '';
                $bank_of_deposit ='';
                $remark ='';
                $bank_account = '';
            }
        }else{
//            $where['source'] = array('in',[4,5,6,9,10]);
            $where['is_income'] = 1;
            if($customer_id>0){
                $ccrow = Customer::get($customer_id);
                $where['obj_id']=$customer_id;
                $company = $ccrow['company'];
                $nickname = $ccrow['contacts'];
                $address = $ccrow['address'];
                $mobile = $ccrow['mobile'];
                $zip_code = $ccrow['zip_code'];
                $tax_number = $ccrow['tax_number'];
                $bank_of_deposit =$ccrow['bank_of_deposit'];
                $remark = $ccrow['remark'];
                $bank_account = $ccrow['bank_account'];
            }
        }


        if($storehouse_id >0){
            $where['storehouse_id'] = $storehouse_id;
        }
        if(empty($end_time)){
            $end_time = time();
        }

        $where['createtime'] =  array('between time',[$start_time,$end_time]);

        $rows = $this->model->where($where)->select();

//        $gids = [];
//        foreach ($list as $v){
//            $gids[] = $v['id'];
//        }
//        $retreatgoods = Db::name('sales_retreat_goods')
//            ->alias('rg')
//            ->join('sales_retreat s','rg.sales_retreat_id=s.id')
//            ->where(array('s.sales_checkout_id'=>array('in',$ids)))
//            ->select();
//        $changegoods = Db::name('sales_change_goods')
//            ->alias('rg')
//            ->join('sales_change s','rg.sales_change_id=s.id')
//            ->where(array('s.sales_checkout_id'=>array('in',$ids)))
//            ->select();
//        foreach ($list as $k=> $v){
//            foreach ($retreatgoods as $val){
//                if($v['goods_id'] == $val['goods_id']){
//                    $list[$k]['goods_num'] -=$val['goods_num'];
//                }
//            }
//            foreach ($changegoods as $val){
//                if($v['goods_id'] == $val['goods_id']){
//                    $list[$k]['goods_num'] -=$val['goods_num'];
//                }
//            }
//        }

        $list = [];
        $source = $this->model->an_source();
        foreach ($rows as $v){
            $set_price = Db::name('analysis_log')->where(array('analysis_id'=>$v['id'],'is_income'=>array('<',3)))->sum('price');
            $dis_price = Db::name('analysis_log')->where(array('analysis_id'=>$v['id'],'is_income'=>3))->sum('price');
            $list[] = array(
                'createtime'=>$v['createtime'],
                'number'=>$v['number'],
                'source'=>$source[$v['source']],
                'operator'=>$v['operator'],
                'cost'=>$v['cost'],
                'settle_name'=>$v['settle_name'],
                'set_price'=>$set_price,//已经结算
                'not_price'=>$v['cost']-$set_price-$dis_price,//没有结算
                'dis_price'=>$dis_price,//抹零
                'explain'=>$v['explain'],//摘要
            );
        }

//        exit;
        //运费 优惠等
        $template_path = config('site.file_url').'/template/caiwu.xlsx';
        $spreadsheet = IOFactory::load($template_path);
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        $worksheet->setTitle('单据分析');

        $len = count($list);
        $rows = $list;

        $allnum = 0;
        $allprice = 0;

        for ($i=0; $i < $len; $i++) {
            $j = $i + 16;
            //从表格第3行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $i+1);
            $worksheet->setCellValueByColumnAndRow(2, $j, date('Y-m-d',$rows[$i]['createtime']));
            $worksheet->setCellValueByColumnAndRow(3, $j, $rows[$i]['number']);
            $worksheet->setCellValueByColumnAndRow(4, $j, $rows[$i]['source']);
            $worksheet->setCellValueByColumnAndRow(5, $j, $rows[$i]['operator']);
            $worksheet->setCellValueByColumnAndRow(6, $j, $rows[$i]['settle_name']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $rows[$i]['cost']);
            $worksheet->setCellValueByColumnAndRow(8, $j, $rows[$i]['set_price']);
            $worksheet->setCellValueByColumnAndRow(9, $j, $rows[$i]['not_price']);
            $worksheet->setCellValueByColumnAndRow(10, $j, $rows[$i]['dis_price']);//
            $worksheet->setCellValueByColumnAndRow(11, $j, $rows[$i]['explain']);//
        }
        if($customer_id || $supplier_id){
            $worksheet->setCellValueByColumnAndRow(2, 2, $company);
            $worksheet->setCellValueByColumnAndRow(2, 4, $nickname);//联系人
            $worksheet->setCellValueByColumnAndRow(2, 5, $address);//地址
            $worksheet->setCellValueByColumnAndRow(2, 6, $mobile);//电话
            $worksheet->setCellValueByColumnAndRow(2, 7, $zip_code);//邮编
            $worksheet->setCellValueByColumnAndRow(2, 8, $tax_number);//税号
            $worksheet->setCellValueByColumnAndRow(2, 9, $bank_of_deposit);//开户银行
            $worksheet->setCellValueByColumnAndRow(2, 10,$bank_account);//公司帐号
            $worksheet->setCellValueByColumnAndRow(2, 11, $remark);//公司备注
        }

        $worksheet->setCellValueByColumnAndRow(2, 12, $start_time);
        $worksheet->setCellValueByColumnAndRow(2, 13, $end_time);

        $filename = '单据分析.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');




    }
    public function getcount($params){
       $where = array();
       foreach ($params as $k=> $v){
            if( $k=='storehouse_name' && !empty($v)){//仓库
                $house = new Storehouse();
                $hrow = $house->where(array('name'=>$v))->find();
                if(!empty($hrow)){
                    $where['a.storehouse_id'] = $hrow['id'];
                }
            }
           if($k == 'operator' && !empty($v)){//经手人
                $where['a.operator'] = $v;
           }
           if($k == 'company' && !empty($v)){//部门
               $where['a.company'] = $v;
           }
           if($k == 'is_income' && !empty($v)){//收支情况
               $where['a.is_income'] = $v;
           }
           if($k == 'settle_name' && !empty($v)){//结算单位
               $where['a.settle_name'] = array('like','%'.$v.'%');
           }
           if($k == 'number' && !empty($v)){//编号
               $where['number'] = $v;
           }
           if($k == 'analysis.createtime' && !empty($v)){//创建时间
               $arr = explode(' - ',$v);
               $where['a.createtime'] = array('between time',$arr);;
           }
           if($k == 'status' && !empty($v)){//状态
               $where['a.status'] = array('in',$v);
           }
       }

        $allcost = Db::name('analysis')->alias('a')->where($where)->sum('cost');

        $where['l.status'] = 1;
        $yicost = Db::name('analysis')
            ->alias('a')
            ->join('analysis_log l','a.id = l.analysis_id ')
            ->where($where)
            ->sum('price');
       
//        $yicost = Db::name('analysis_log')
//            ->alias('l')
//            ->join('analysis a',' l.analysis_id =  a.id ')
//            ->where($where)
//            ->sum('price');

        return array(
          'allcost'=>$allcost,
          'yescost'=>$yicost,
          'notcost'=>bcsub($allcost,$yicost,2),
        );
    }
    public function batchsss(){
        if($this->request->isAjax()){
            $collect_money = input('collect_money');//结算金额
            $discount = input('discount');//优惠金额
            $pay_type = input('pay_type/d',0);//是否收支
            $customer_id = input('customer_id/d',0);//客户
            $supplier_id = input('supplier_id/d',0);//供应商
            $make_time = input('make_time');//制单时间
            $pay_time = input('pay_time');//过账时间
            $pay_id = input('pay_id');//是否收入
            $thumb = input('thumb');//凭证
            $remark = input('remark');//备注
            $data = input('row/a');

            if (empty($data)){
                $this->error('单据异常1');
            }
            $ids = [];
            foreach ($data as $v){
                $ids[] = $v['id'];
            }


            if(empty($thumb) && empty($remark)){
                $this->error('凭证或备注至少选一项');
            }

            $paymoney = 0;
            foreach ($data as $v){
                $paymoney +=$v['paymoney'];
            }
//            dump($paymoney-$discount);
//            dump($collect_money);
//            dump(bccomp($paymoney-$discount,$collect_money,2));
//            if($paymoney-$discount != $collect_money){
            if(bccomp($paymoney-$discount,$collect_money,2) != 0){
                $this->error('结算金额不匹配');
            }
            $where = array(
                'is_income'=>$pay_type,
                'status'=>array('<',3),
                'id'=>array('in',$ids)
            );
            if($pay_type == 1){
                $where['obj_id'] = $customer_id;
                $obj_id = $customer_id;
                $setrow = Db::name('customer')->where(array('id'=>$customer_id))->find();
                $settle_name = $setrow['company'];
                $list = Db::name('analysis')->where($where)->select();
            }else{
                $where['obj_id'] = $supplier_id;
                $obj_id = $supplier_id;
                $setrow = Db::name('supplier')->where(array('id'=>$supplier_id))->find();
                $settle_name = $setrow['nickname'];
                $list = Db::name('analysis')->where($where)->select();
            }
            $storehouse_id = 0;
            foreach ($list as $v){
                if(empty($storehouse_id)){
                    $storehouse_id = $v['storehouse_id'];
                }
                if($storehouse_id != $v['storehouse_id']){
                    $this->error('单据归属地异常');
                }
            }
            $no_num = 0;
            foreach ($list as $value){
                foreach ($data as $v){
                    if($value['id'] == $v['id']){
                        if(bccomp($v['paymoney'],$value['cost'],2) !== 0){
                            $no_num++;
                        }
                    }
                }
            }

            if($no_num >1){
                $this->error('仅限一个单据金额改动');
            }
//分摊单据
            $num = Db::name('analysis_collection')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            $analysis_id = 0;
            //创建收款单
            $cdata = array(
                'number'=>'XS-T-'.date('Y-m-d').'-'.getnumber($num),
                'paymoney'=>$collect_money,
                'image'=>$thumb,
                'remark'=>$remark,
                'is_income'=>$pay_type,
                'admin_id' => session('admin')['id'],
                'group_id' => $group['group_id'],
                'pay_time'=>strtotime(input('pay_time')),
                'make_time'=>strtotime(input('make_time')),
                'company' => $group['name'],
                'settle_name' => $settle_name,
                'operator' => session('admin')['nickname'],
                'storehouse_id' => $storehouse_id,
                'pay_id'=>$pay_id,
                'obj_id'=>$obj_id,
                'discount'=>$discount,
                'createtime'=>time(),
            );
            $analysis_id = 0;//优惠的单据ID





            Db::startTrans();
            try {
                $collect_id = Db::name('analysis_collection')->insertGetId($cdata);
                if(!$collect_id){
                    throw new Exception('单据创建失败');
                }
                $vdata = array(
                    'image'=>$thumb,
                    'remark'=>$remark,
                    'type'=>17,
                    'is_go'=>3,
                    'source_id'=>$collect_id,
                );

                $Voucher = new Voucher;
                $Voucher->save($vdata);

                //挨个处理
                foreach ($data as $value) {
                    $row = Db::name('analysis')->where(array('id' => $value['id']))->find();
                    $paymoney = Db::name('analysis_log')->where(array('analysis_id' => $value['id'], 'status' => 1))->sum('price');
                    if (bcadd($value['paymoney'],$paymoney,2)   > $row['cost']) {
                        throw new Exception('金额异常');
                    }
                    if(bcadd($value['paymoney'] , $paymoney,2) == $row['cost']){
                        $state = 3;
                    }else{
                        //计算优惠金额加进去是否完成
                        if(bcadd(bcadd($value['paymoney'] , $paymoney,2),$discount,2) == $row['cost']){
                            $analysis_id = $row['id'];
                            $state = 3;
                        }else{
                            $state = 2;
                        }

                    }
                    //不够的单独处理
                    $res = Db::name('analysis')->where(array('id'=>$value['id']))->update(array('status'=>$state));
//                    if(empty($res)){
//                        throw new Exception('单据异常');
//                    }
                    $data = array(
                        'analysis_collection_id'=>$collect_id,
                        'analysis_id'=>$value['id'],
                        'price'=>$value['paymoney'],
                        'image'=>$thumb,
                        'remark'=>$remark,
                        'is_income'=>$row['is_income'],
                        'admin_id' => session('admin')['id'],
                        'group_id' => $group['group_id'],
                        'pay_time'=>strtotime(input('pay_time')),
                        'make_time'=>strtotime(input('make_time')),
                        'company' => $group['name'],
                        'settle_name' => $row['settle_name'],
                        'operator' => session('admin')['nickname'],
                        'storehouse_id' => $row['storehouse_id'],
                        'handler' => $row['operator'],
                        'handler_id' => $row['admin_id'],
                        'pay_id'=>$pay_id,
                        'obj_id'=>$obj_id,
                    );
                    $Log = new Log;
                    $Log->save($data);
//                    Db::name('')
                }
                //优惠不为空
                if(!empty($discount)){
                    if(empty($analysis_id)){
                        $analysis_id = $list[count($list)-1]['id'];
                    }

                    $rerre = Db::name('analysis_log')->insert(array(
                        'price'=>$discount,
                        'analysis_id'=>0,
                        'image'=>$thumb,
                        'remark'=>$remark,
                        'is_income'=>3,
                        'admin_id' => session('admin')['id'],
                        'group_id' => $group['group_id'],
                        'pay_time'=>strtotime($pay_time),
                        'make_time'=>strtotime($make_time),
                        'company' => $group['name'],
                        'settle_name' => $settle_name,
                        'operator' => session('admin')['nickname'],
                        'storehouse_id' => $row['storehouse_id'],
                        'handler' => $row['operator'],
                        'handler_id' => $row['admin_id'],
                        'pay_id'=>$pay_id,
                        'createtime'=>time(),
                        'analysis_collection_id'=>$collect_id,
                    ));
                    if(!$rerre){
                        throw new Exception('联系管理员');
                    }
                }
                Db::commit();
                return array(
                  'code'=>1,
                  'msg'=>'操作成功',
                );
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

        }
        $paymodel = new \app\common\model\coll\Pay();
        $plist = $paymodel->where(array('status'=>'normal'))->select();
        $this->assign('plist',$plist);
        return $this->view->fetch();
    }
    public function getanalysis(){
        if($this->request->isAjax()){
            $pay_type = input('pay_type');
            $source_id = input('source_id');
            $where = array(
                'is_income'=>$pay_type,
                'obj_id'=>$source_id,
                'status'=>array('<',3),
                'id'=>array('in',json_decode(input('ids'),true))
            );
            if($pay_type == 1){
                $list = Db::name('analysis')->where($where)->select();
//                $total = Db::name('analysis')->where($where)->count();
            }
            if($pay_type == 2){
                $list = Db::name('analysis')->where($where)->select();
//                $total = Db::name('analysis')->where($where)->count();
            }
//            dump($where);
//            dump($list);
            $houses = Db::name('storehouse')->select();
            $source = $this->model->an_source();
            $statuss = $this->model->an_status();
            foreach ($list as $k=>$v){
                $list[$k]['createtime'] = date('Y-m-d',$v['createtime']);
                foreach ($houses as $val){
                    if($val['id'] == $v['storehouse_id']){
                        $list[$k]['house_name'] = $val['name'];
                    }
                }
                $list[$k]['source'] = $source[$v['source']];
                $Log = new Log;

                if($v['status'] == 1){
                    $list[$k]['paymoney'] = $v['cost'];
                }else{
                    $paymoney = $Log->where(array('analysis_id'=>$v['id'],'status'=>1))->sum('price');
                    $list[$k]['paymoney'] = bcsub ($v['cost'],$paymoney,2);
                }


//                $list[$k]['ystatus'] = $v['status'];
//                $list[$k]['status'] = $statuss[$v['status']];
            }
//            dump($list);
            $result = $list;

            return json($result);
        }
    }
    public function seach(){
        $pay_type = input('pay_type');
        $source_id = input('source_id');
        if($this->request->isAjax()){
            $where = array(
                'is_income'=>$pay_type,
                'obj_id'=>$source_id,
                'status'=>array('<',3)
            );
            $offset = input('offset/d',0);
            $limit = input('limit/d',0);
            if($pay_type == 1){
                $list = Db::name('analysis')->where($where)->limit($offset,$limit)->select();
                $total = Db::name('analysis')->where($where)->count();
            }
            if($pay_type == 2){
                $list = Db::name('analysis')->where($where)->limit($offset,$limit)->select();
                $total = Db::name('analysis')->where($where)->count();
            }
            $houses = Db::name('storehouse')->select();
            $source = $this->model->an_source();
            $statuss = $this->model->an_status();
            foreach ($list as $k=>$v){
                foreach ($houses as $val){
                    if($val['id'] == $v['storehouse_id']){
                        $list[$k]['house_name'] = $val['name'];
                    }
                }
                $list[$k]['source'] = $source[$v['source']];
                $Log = new Log;

                if($v['status'] == 1){
                    $list[$k]['paymoney'] = $v['cost'];
                }else{
                    $paymoney = $Log->where(array('analysis_id'=>$v['id'],'status'=>1))->sum('price');
                    $list[$k]['paymoney'] = bcsub ($v['cost'],$paymoney,2);
                }


//                $list[$k]['ystatus'] = $v['status'];
//                $list[$k]['status'] = $statuss[$v['status']];
            }

            $result = array("total" => $total, "rows" => $list);
            return $result;
        }
        $this->assign('pay_type',$pay_type);
        $this->assign('source_id',$source_id);
        return $this->view->fetch();
    }
    public function getconfig(){
        $list = $this->model->an_status();
        return $list;
    }

}
